package com.zzy.accessdecision.accessDecision;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author Lucas-zhang
 * @description TODO
 * @date 2022-03-25 13:56
 */
public class CustomAccessDecisionManager implements AccessDecisionManager {
    /**
     * 权限决策
     * @param authentication 已认证用户对象
     * @param object    包含请求相关信息的FilterInvocation
     * @param configAttributes 当前请求所需要的角色信息
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        // 获取认证的用户所具有的角色权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        // 循环遍历当前请求所需的角色信息，只要有一个满足就可以
        for (ConfigAttribute configAttribute : configAttributes) {

            // 该请求在数据库中不具备角色
            if ("ROLE_null".equals(configAttribute.getAttribute()) && authentication instanceof UsernamePasswordAuthenticationToken) {
                return;
            }

            // 轮询判断用户的角色权限是否符合当前资源请求的所需要的权限
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(configAttribute.getAttribute())){
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，无法访问!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
